﻿/********************************************************
 * Module Name    : Request TrreView-Toolbar button
 * Purpose        : Request button action and show pop-up under Arequest (TreeViewItem || Toolbar)
 * Class Used     : 
 * Chronological Development
 * Harwinder Singh      25-July-2011
 ******************************************************/
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Logging;
using VAdvantage.Utility;
using System.Text;
using VAdvantage.Model;
using VAdvantage.Grids;
using VAdvantage.Panels;
using System.ComponentModel;

namespace VAdvantage.Apps
{
    public class ARequest
    {
        #region "Declaration"

        /**	The Table						*/
        private int m_AD_Table_ID;
        /** The Record						*/
        private int m_Record_ID;
        /** BPartner						*/
        private int m_C_BPartner_ID;

        //private System.Windows.Forms.ToolStripMenuItem m_new;
        //New Item
        private ATreeViewItem m_new;
        /* actine Item */
        private ATreeViewItem m_active;
        /* All Item */
        private ATreeViewItem m_all;

        //private System.Windows.Forms.ToolStripMenuItem m_active;
        //private System.Windows.Forms.ToolStripMenuItem m_all;

        /* where condition */
        private System.Text.StringBuilder m_where;

        /**	Logger	*/
        private static VLogger log = VLogger.GetVLogger(typeof(ARequest).FullName);

        // Calling (Parent) Item
        ATreeViewItem invoker = null;

        //Busy indicator
        IBusy _iBusy = null;
        #endregion

        /// <summary>
        ///	Constructor
        /// </summary>
        /// <param name="invoker">Tol Strip drop down invoker button</param>
        /// <param name="AD_Table_ID">Table</param>
        /// <param name="Record_ID">record</param>
        /// <param name="C_BPartner_ID">optinal BP</param>
        /// 
        public ARequest(AppsAction invoker, int AD_Table_ID, int Record_ID,
            int C_BPartner_ID, IBusy iBusy)
        {

            _iBusy = iBusy;

            log.Config("AD_Table_ID=" + AD_Table_ID + ", Record_ID=" + Record_ID);
            m_AD_Table_ID = AD_Table_ID;
            m_Record_ID = Record_ID;
            m_C_BPartner_ID = C_BPartner_ID;
            GetRequests(invoker);
           
        }	//	ARequest

        /// <summary>
        /// Add Request tree view items
        /// </summary>
        /// <param name="invoker"></param>
        private void GetRequests(AppsAction item)
        {
            invoker = item.GetTreeViewItem();

            //Check User Re-Click onParent Item

            if (invoker.Items.Count > 0) //Has Already Processed
            {
                SetBusy(false);
                return;
            }

            m_new = new ATreeViewItem();
            m_new.Header = Msg.GetMsg(Envs.GetCtx(), "RequestNew");
            m_new.Icon = Envs.LoadImageSource("New16.png");

            invoker.Items.Add(m_new);

            m_new.Click += new RoutedEventHandler(ActionPerformed);

            int activeCount = 0;

            int inactiveCount = 0;
            m_where = new StringBuilder();

            BackgroundWorker worker = new BackgroundWorker();

            worker.DoWork += (sd, cd) =>
            {

                m_where.Append("(AD_Table_ID=").Append(m_AD_Table_ID)
                    .Append(" AND Record_ID=").Append(m_Record_ID)
                    .Append(")");
                //
                if (m_AD_Table_ID == MUser.Table_ID)
                    m_where.Append(" OR AD_User_ID=").Append(m_Record_ID)
                        .Append(" OR SalesRep_ID=").Append(m_Record_ID);
                else if (m_AD_Table_ID == MBPartner.Table_ID)
                    m_where.Append(" OR C_BPartner_ID=").Append(m_Record_ID);
                else if (m_AD_Table_ID == MOrder.Table_ID)
                    m_where.Append(" OR C_Order_ID=").Append(m_Record_ID);
                else if (m_AD_Table_ID == MInvoice.Table_ID)
                    m_where.Append(" OR C_Invoice_ID=").Append(m_Record_ID);
                else if (m_AD_Table_ID == MPayment.Table_ID)
                    m_where.Append(" OR C_Payment_ID=").Append(m_Record_ID);
                else if (m_AD_Table_ID == MProduct.Table_ID)
                    m_where.Append(" OR M_Product_ID=").Append(m_Record_ID);
                else if (m_AD_Table_ID == MProject.Table_ID)
                    m_where.Append(" OR C_Project_ID=").Append(m_Record_ID);
                //else if (m_AD_Table_ID == MCampaign.Table_ID)
                //    m_where.Append(" OR C_Campaign_ID=").Append(m_Record_ID);
                else if (m_AD_Table_ID == MAsset.Table_ID)
                    m_where.Append(" OR A_Asset_ID=").Append(m_Record_ID);
                //
                String sql = "SELECT Processed, COUNT(*) "
                    + "FROM R_Request WHERE " + m_where
                    + " GROUP BY Processed "
                    + "ORDER BY Processed DESC";
                System.Data.IDataReader dr = null;
                try
                {
                    dr = VAdvantage.DataBase.DB.ExecuteReader(sql, null);
                    while (dr.Read())
                    {
                        if ("Y".Equals(dr[0].ToString()))
                            inactiveCount = Util.GetValueOfInt(dr[1]);
                        else
                            activeCount += Util.GetValueOfInt(dr[1]);
                    }
                    dr.Close();
                }
                catch (Exception e)
                {
                    if (dr != null)
                    {
                        dr.Close();
                        dr = null;
                    }
                    log.Log(Level.SEVERE, sql, e);
                }
            };

            worker.RunWorkerCompleted += (sc, cc) =>
            {

                //
                if (activeCount > 0)
                {
                    //m_active = new System.Windows.Forms.ToolStripMenuItem(Msg.GetMsg(Env.GetContext(), "RequestActive")
                    //    + " (" + activeCount + ")");

                    m_active = new ATreeViewItem()
                    {
                        Header = Msg.GetMsg(Envs.GetCtx(), "RequestActive")
                            + " (" + activeCount + ")"
                    };

                    invoker.Items.Add(m_active);
                    m_active.Click += ActionPerformed;

                    if (inactiveCount > 0)
                    {
                        //m_all = new System.Windows.Forms.ToolStripMenuItem(Msg.GetMsg(Env.GetContext(), "RequestAll")
                        //    + " (" + (activeCount + inactiveCount) + ")");

                        m_all = new ATreeViewItem()
                        {
                            Header = Msg.GetMsg(Envs.GetCtx(), "RequestAll")
                                + " (" + (activeCount + inactiveCount) + ")"
                        };

                        invoker.Items.Add(m_all);
                        m_all.Click += ActionPerformed;
                    }
                }
                SetBusy(false);

                invoker.IsExpanded = true;// .ShowDropDown();
            };

            worker.RunWorkerAsync();
        }

        /// <summary>
        /// Item Click event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ActionPerformed(object sender, EventArgs e)
        {

            Classes.Query query = null;

            ATreeViewItem tp = (ATreeViewItem)sender;
            string actionCommand = tp.Header.ToString();
            if (m_active != null && m_active.Header.Equals(actionCommand))
            {
                query = new Classes.Query("");
                String where = "(" + m_where + ") AND Processed='N'";
                query.AddRestriction(where);
            }
            else if (m_all != null && m_all.Header.Equals(actionCommand))
            {
                query = new Classes.Query("");
                query.AddRestriction(m_where.ToString());
            }


            int AD_Window_ID = 232;		//	232=all - 201=my
            //System.Windows.Forms.ContainerControl cnCtl = null;

            Object cnCtl = null;
            //cnCtl = (System.Windows.Forms.ContainerControl)tp.OwnerItem.Owner.Parent;

            if (cnCtl != null)
            {
                // cnCtl.ParentForm.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            }

            AWindow frame = new AWindow();


            frame.Initialized += (si, ei) =>
            {

                if (m_new.Header.Equals(actionCommand))
                {
                    //
                    GridTab tab = frame.GetAPanel().GetCurrentTab();
                    GridController gc = frame.GetAPanel().GetCurrentGC();

                    gc.OnNewRowInserted += (sn, en) =>
                    {
                        tab.SetValue("AD_Table_ID", m_AD_Table_ID);
                        tab.SetValue("Record_ID", m_Record_ID);
                        //

                        if (m_C_BPartner_ID != 0)
                            tab.SetValue("C_BPartner_ID", m_C_BPartner_ID);
                        //
                        System.Threading.ThreadPool.QueueUserWorkItem(delegate
                        {
                            if (m_AD_Table_ID == MBPartner.Table_ID)
                                tab.SetValue("C_BPartner_ID", m_Record_ID);
                            else if (m_AD_Table_ID == MUser.Table_ID)
                                tab.SetValue("AD_User_ID", m_Record_ID);
                            //
                            else if (m_AD_Table_ID == MProject.Table_ID)
                                tab.SetValue("C_Project_ID", m_Record_ID);
                            else if (m_AD_Table_ID == MAsset.Table_ID)
                                tab.SetValue("A_Asset_ID", m_Record_ID);
                            //
                            else if (m_AD_Table_ID == MOrder.Table_ID)
                                tab.SetValue("C_Order_ID", m_Record_ID);
                            else if (m_AD_Table_ID == MInvoice.Table_ID)
                                tab.SetValue("C_Invoice_ID", m_Record_ID);
                            //
                            else if (m_AD_Table_ID == MProduct.Table_ID)
                                tab.SetValue("M_Product_ID", m_Record_ID);
                            else if (m_AD_Table_ID == MPayment.Table_ID)
                                tab.SetValue("C_Payment_ID", m_Record_ID);
                            //
                            else if (m_AD_Table_ID == MInOut.Table_ID)
                                tab.SetValue("M_InOut_ID", m_Record_ID);
                        });
                        //
                        //else if (m_AD_Table_ID == MCampaign.Table_ID)
                        //    tab.SetValue("C_Campaign_ID", m_Record_ID);
                    };
                    gc.OnManualRowInserting += (sm, evm) =>
                    {
                        gc.AddNewRow(false);
                    };

                }
                Dispose();
                //frame.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;

                if (cnCtl != null)
                {
                    // cnCtl.ParentForm.Cursor = System.Windows.Forms.Cursors.Default;
                }
                frame.ShowAPanel();

                tp = null;
                cnCtl = null;
            };

            if (!frame.InitWindow(AD_Window_ID, query))
            {
                if (cnCtl != null)
                {
                    //cnCtl.ParentForm.Cursor = System.Windows.Forms.Cursors.Default;
                }
                return;
            }

        }



        /// </summary>
        private void Dispose()
        {
            if (invoker != null)
            {
                invoker.Items.Clear();
            }

            if (m_new != null)
            {
                m_new.Click -= ActionPerformed;
                m_new = null;
            }
            if (m_active != null)
            {
                m_active.Click -= ActionPerformed;
                m_active = null;
            }
            if (m_all != null)
            {
                m_all.Click -= ActionPerformed;
                m_all = null;
            }
            _iBusy = null;

        }

        private void SetBusy(bool isBusy)
        {
            if (_iBusy != null)
            {
                _iBusy.SetBusy(isBusy);
            }
        }
    }
}
